{% extends "auth_base.html" %}

{% block title %}快速设置{% endblock %}

{% block header %}快速设置{% endblock %}
{% block subheader %}完成即可直接启动使用基础对话功能{% endblock %}

{% block content %}
<div class="auth-wrapper">
    <form id="quickSetupForm" onsubmit="handleQuickSetup(event)">
        <div class="mb-2">
            <label for="inputField" class="form-label">要监听的用户列表（请使用微信昵称，不要使用备注名）</label>
            <input type="text" class="form-control" id="inputField" placeholder="请输入用户昵称，多个用户请用英文逗号分隔" required>
            <small class="form-text text-muted">多个用户请用英文逗号分隔，例如：小明,小红,群名称</small>
        </div>

        <div class="d-flex justify-content-between mb-2">
            <button type="button" class="btn btn-secondary" onclick="skipSetup()">跳过</button>
            <button type="submit" class="btn btn-primary">下一步</button>
        </div>
    </form>
</div>

<div id="apiKeySection" style="display: none; margin-top: 10px;">
    <div class="mb-2">
        <label for="apiKey" class="form-label">API密钥</label>
        <input type="text" class="form-control" id="apiKey" placeholder="请输入API密钥" required>
        <small class="form-text text-muted">
            还没有API密钥？<a href="https://api.kourichat.com/register" target="_blank" rel="noopener">点我获取</a>
        </small>
    </div>

    <div class="d-flex justify-content-between mb-2">
        <button type="button" class="btn btn-secondary" onclick="skipSetup()">跳过</button>
        <button type="button" class="btn btn-primary" onclick="saveSetup()">保存设置</button>
    </div>
</div>

<!-- 错误提示框 -->
<div id="errorAlert" class="alert alert-danger alert-dismissible fade show" role="alert" style="display: none;">
    <span id="errorMessage"></span>
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endblock %}

{% block extra_script %}
<script>
    function handleQuickSetup(event) {
        event.preventDefault();
        
        const inputField = document.getElementById('inputField').value.trim();
        
        if (inputField === '') {
            showError('请输入至少一个用户昵称');
            return;
        }

        // 显示API密钥输入框
        document.getElementById('quickSetupForm').style.display = 'none';
        document.getElementById('apiKeySection').style.display = 'block';
    }

    function saveSetup() {
        const inputField = document.getElementById('inputField').value.trim();
        const apiKey = document.getElementById('apiKey').value.trim();
        
        if (inputField === '') {
            showError('请输入至少一个用户昵称');
            return;
        }
        
        if (apiKey === '') {
            showError('请输入API密钥');
            return;
        }

        // 处理用户列表
        const userList = inputField.split(',')
            .map(item => item.trim())
            .filter(item => item !== '');
            
        if (userList.length === 0) {
            showError('请输入有效的用户昵称');
            return;
        }

        // 发送数据到服务器
        fetch('/save_quick_setup', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                listen_list: userList,
                api_key: apiKey
            })
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(data => {
            if (data.status === 'success') {
                // 显示成功消息
                const successMessage = document.createElement('div');
                successMessage.className = 'alert alert-success';
                successMessage.textContent = '设置已保存，即将跳转到仪表盘...';
                document.querySelector('.auth-wrapper').appendChild(successMessage);
                
                // 延迟跳转
                setTimeout(() => {
                    window.location.href = '/dashboard';
                }, 1500);
            } else {
                showError(data.message || '保存设置失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showError('保存失败：' + (error.message || '网络错误，请重试'));
        });
    }

    function skipSetup() {
        // 跳过设置，直接重定向到仪表盘
        window.location.href = '/dashboard';
    }

    function showError(message) {
        const alert = document.getElementById('errorAlert');
        const errorMessage = document.getElementById('errorMessage');
        
        if (alert && errorMessage) {
            errorMessage.textContent = message;
            alert.style.display = 'block';
            
            // 3秒后自动隐藏
            setTimeout(() => {
                alert.style.display = 'none';
            }, 3000);
        } else {
            // 如果找不到错误提示框，使用alert
            alert(message);
        }
    }
</script>
{% endblock %} 